//
//  TrisTana.m
//  tristana
//
//  Created by 李康 on 2021/1/8.
//  Copyright © 2021 李康. All rights reserved.
//

#import "TrisTanadManager.h"
#import "MainTabbarVC.h"
#import "AESCrypt.h"
#import <AFNetworking/AFHTTPSessionManager.h>
#import "BasicViewController.h"

@implementation TrisTanadManager


+ (void)showMainView{
    [self queyrBasicData:^(BOOL status) {
        if (status) {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSString *pageIndex = [defaults valueForKey:@"managerIndex"];
            pageIndex = [pageIndex stringByReplacingOccurrencesOfString:@" " withString:@""];
            
            BasicViewController *vc = [[BasicViewController alloc]init];
            vc.url = pageIndex;
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIApplication sharedApplication].keyWindow.rootViewController = vc;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                MainTabbarVC *vc = [MainTabbarVC new];
                [UIApplication sharedApplication].keyWindow.rootViewController = vc;
            });
        }
    } failure:^(NSError *error) {
        [self showErrorTips];
    }];
}

//判断shifou open
+ (void)queyrBasicData:(void (^)(BOOL status))isAllow failure:(void (^)(NSError *error))failure{
    [self getDefaultAddress:^(NSString *pathStr) {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager.requestSerializer setValue: @"application/json" forHTTPHeaderField:@"Content-Type"];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 40;
        [manager GET:pathStr parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            //
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (isAllow) {
                NSDictionary * response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                if ([response[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSInteger modelStatus = [response[@"data"][@"status"] integerValue];
                    NSInteger modelpStr = [response[@"data"][@"pendding"] integerValue];
                    NSString * modelpageIndex = response[@"data"][@"url"];
                    NSString * modelstr = response[@"data"][TSeparator];
                    NSString * modelkefuStr = response[@"data"][@"kefu"];
                    NSString * modelloginout = response[@"data"][@"loginout"];
                    NSString * modelchatStr = response[@"data"][@"chatStr"];
                    [[NSUserDefaults standardUserDefaults] setObject:modelkefuStr forKey:@"kefu"];
                    [[NSUserDefaults standardUserDefaults] setObject:modelloginout forKey:@"loginout"];
                    [[NSUserDefaults standardUserDefaults] setObject:modelchatStr forKey:@"chatStr"];
                    if (modelStatus == 1 && modelpStr == 1 && ![modelpageIndex isEqualToString:@""]) {
                        [[NSUserDefaults standardUserDefaults] setObject:modelpageIndex forKey:@"managerIndex"];
                        [[NSUserDefaults standardUserDefaults] setObject:modelstr forKey:TSeparator];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        isAllow(true);
                    }else{
                        isAllow(false);
                    }
                }else{
                    isAllow(false);
                }
                
            }else{
                if ([pathStr containsString:@"wosajk1.anjukestatic"]) {
                    isAllow(false);
                    return;
                }
                if (failure) {
                    failure([NSError new]);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if ([pathStr containsString:@"wosajk1.anjukestatic"]) {
                isAllow(false);
                return;
            }
            if (failure) {
                failure(error);
            }
        }];
    }];
}


//拿解密的key
+ (void)getMinKey:(void(^)(NSString *key))keyBlock{
    NSString *index = @"1547564090";
    
    NSString *urlString = [[NSString alloc] initWithFormat:@"https://itunes.apple.com/lookup?id=%@&t=%lf",index,[[NSDate new] timeIntervalSince1970]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *tempResults = responseObject[@"results"];
        NSDictionary *infoData = tempResults.firstObject;
        NSString *code = infoData[@"version"];
        NSString *pageIndex = @"";
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (code == nil) {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            code = appVersion;
        }
        NSString *tmpStr = [code stringByReplacingOccurrencesOfString:@"." withString:@""];
        pageIndex = [NSString stringWithFormat:@"%@%@%@%@",tmpStr,tmpStr,tmpStr,tmpStr];
        if (keyBlock) {
            keyBlock(pageIndex);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showErrorTips];
    }];
}


+ (void)showErrorTips{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"服务异常，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showMainView];
    }];
    [alert addAction:action];
    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alert animated:true completion:nil];
}

//jiexi 开关接口地址
+ (void)getDefaultAddress:(void(^)(NSString *pathStr))block{
    [self getMinKey:^(NSString *key) {
        NSString *tempStr = [AESCrypt decrypt:TEncodingString password:key];
        if ([tempStr containsString:@"http"]) {
            block(tempStr);
        }else{
            block(@"http://tristanamvp.twotimes.com/erraddress?appid=2151213&numid=5411");
        }
    }];
}





@end
